package com.bjpowernode.interceptor;
import com.bjpowernode.beans.User;
import com.bjpowernode.services.UserServices;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


//拦截器拦截一切*.action
public class MyLoginInterceptor implements HandlerInterceptor {

    @Autowired
    UserServices userServices;


    //请求之前
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        Object user = session.getAttribute("user");
        if(user==null){
            //获取cookies里面的用户账号和密码，并且再次进入数据库验证，如果验证成功，也可以进去（免登录）
            //取出cookies的属性和值（使用请求对象HttpServletRequest取得cookies）
            String loginAct="";
            String loginPwd="";
            Cookie[] cookies = request.getCookies();
            for (Cookie cookie : cookies) {
                if(cookie.getName().equals("loginAct")){
                    System.out.println("找到了loginAct的cookies其值为："+cookie.getValue());
                    loginAct = cookie.getValue();
                }
                if(cookie.getName().equals("loginPwd")){
                    System.out.println("找到了loginPwd的cookies其值为："+cookie.getValue());
                    loginPwd= cookie.getValue();
                }
            }
            User userTemp = userServices.login(loginAct, loginPwd);
            if(userTemp==null){
                System.out.println("已经拦截了："+request.getRequestURI());
                response.sendRedirect("/static/login.html");
                return false;
            }
            else{
                //需要添加HttpSession
                session.setAttribute("user",userTemp);
                return true;
            }
        }
        //返回true放行，返回false不放行
        return true;
    }

    //请求成功，准备返回到界面
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    //响应成功
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
